package com.beesphere.products.throttling;

import java.util.concurrent.atomic.AtomicBoolean;

public abstract class AbstractUnitOfWork implements UnitOfWork {
	
	private static final long serialVersionUID = -7245175987853244819L;
	
	public static final String OWNER 	= "UOW-OW";
	public static final String ID 		= "UOW-ID";
	
	private String owner;
	private String id;
	private Throwable error;
	
	private final AtomicBoolean finished = new AtomicBoolean (false);
	private final AtomicBoolean canceled = new AtomicBoolean (false);

	public AbstractUnitOfWork (String owner, String id) {
		setOwner (owner);
		setId (id);
	}
	
	public AbstractUnitOfWork (String id) {
		this (null, id);
	}
	
	public AbstractUnitOfWork () {
		this (null);
	}
	
	@Override
	public String getOwner () {
		return owner;
	}

	public void setOwner (String owner) {
		if (owner == null || owner.isEmpty ()) {
			owner = OWNER;
		}
		this.owner = owner;
	}

	@Override
	public String getId () {
		return id;
	}

	public void setId (String id) {
		if (id == null || id.isEmpty ()) {
			id = ID;
		}
		this.id = id;
	}

	@Override
	public void setError (Throwable error) {
		this.error = error;
	}

	@Override
	public Throwable getError () {
		return error;
	}

	@Override
	public boolean isFinished () {
		return finished.get ();
	}

	@Override
	public void setFinished (boolean finished) {
		this.finished.set (finished);
	}
	
	@Override
	public boolean isCanceled () {
		return canceled.get ();
	}

	@Override
	public void setCanceled (boolean canceled) {
		this.canceled.set (canceled);
	}

	@Override
	public void release () {
		error = null;
		finished.set (false);
		canceled.set (false);
	}


}
